package com.naizhuai.ui.task;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.gson.Gson;
import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.adapter.StaticPagerAdapter;
import com.naizhuai.Model.AccountHelper;
import com.naizhuai.Model.db.user.PersonUserBean;
import com.naizhuai.R;
import com.naizhuai.network.NetWorkObserver;
import com.naizhuai.network.exception.ValidateException;
import com.naizhuai.ui.BaseActivity;
import com.naizhuai.ui.entity.CommonLabel;
import com.naizhuai.ui.adapter.ChosenChargeJoinAdapterHolder;
import com.naizhuai.ui.adapter.GridSpacingItemDecoration;
import com.naizhuai.ui.adapter.SpacesItemDecoration;
import com.naizhuai.ui.components.LabelsView;
import com.naizhuai.ui.entity.AddQuestion;
import com.naizhuai.ui.entity.ImgBean;
import com.naizhuai.ui.entity.NormalQAPage;
import com.naizhuai.ui.entity.Task.BehaviorRecommendation;
import com.naizhuai.ui.entity.UserLeader;
import com.naizhuai.ui.entity.mainbusiness.ActionBaseBean;
import com.naizhuai.ui.mianbusiness.action.ActionDetailTxtCreateActivity;
import com.naizhuai.ui.mianbusiness.setting.UserListChosenActivity;
import com.naizhuai.ui.task.adapter.ImageSelectorAdapter;
import com.naizhuai.ui.task.adapter.LabelDailogAdapter;
import com.naizhuai.ui.task.adapter.TaskTypeAdapter;
import com.naizhuai.ui.task.deliverentity.TaskType;
import com.naizhuai.ui.user.UserManageDataApiStoreIml;
import com.naizhuai.util.AlbumUtils;
import com.naizhuai.util.BitmapUtils;
import com.naizhuai.util.ConstantsState;
import com.naizhuai.util.DialogUtils;
import com.naizhuai.util.IntentUtils;
import com.naizhuai.util.MathUtils;
import com.naizhuai.util.ViewUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;
import rx.schedulers.Schedulers;
import rx.subjects.PublishSubject;

import static com.naizhuai.ui.mianbusiness.target.TargetCreateActivity.CHARGE_KEY;
import static com.naizhuai.ui.mianbusiness.target.TargetCreateActivity.CHOSE_CHARGE;
import static com.naizhuai.ui.mianbusiness.target.TargetCreateActivity.CREATE_TARGET_PAGER;

public class ActionSetting1Activity extends BaseActivity {
    public static final String PAGESTATE = "pagestate";
    public static final int CORRELATE = 0;
    public static final int NOCORRELATE = 1;
    public static final int ONLYDISPLAY = 2;
    public static final String In_the_organization="";
    public static final String in_the_team="-1";

    @BindView(R.id.label_detial)
    TextView labelDetial;


    private int currentState;

    private boolean isHandle=true;
    public static void start(Context context) {
        Intent intent = new Intent(context, ActionSetting1Activity.class);
        context.startActivity(intent);
    }

    private String questionId = "";

    private String schemeId = "";

    private String taskFlowId;

    @BindView(R.id.select_user)
    ImageView selectUser;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.ed_question)
    EditText edQuestion;
    @BindView(R.id.view_pager)
    RollPagerView mViewPager;
    @BindView(R.id.selectView)
    RecyclerView selectView;
    @BindView(R.id.lead_label)
    LabelsView leadLabel;
    @BindView(R.id.labal_container)
    LinearLayout labalContainer;
    //標簽數據以及標簽選擇
    @BindView(R.id.label1)
    TextView label1;
    @BindView(R.id.label2)
    TextView label2;
    @BindView(R.id.label3)
    TextView label3;
    @BindView(R.id.label4)
    TextView label4;
    @BindView(R.id.label5)
    TextView label5;
    @BindView(R.id.label6)
    TextView label6;
    @BindView(R.id.btn_next_step)
    Button btnNextStep;
    @BindView(R.id.btn_receive_question)
    Button btnReceiveQuestion;
    @BindView(R.id.cycle_select)
    RecyclerView cycleSelect;

    private TextView[] labels;
    private List<CommonLabel> selectorLabel = new ArrayList<>(6);
    private List<CommonLabel> initListLabel = new ArrayList<>(6);
    private String labelsRoot_5;
    ImageNormalAdapter galleryAdapter;
    private ArrayList<String> mChoiceImages = new ArrayList<>();
    private OptionsPickerView pvLabelOptions;
    private TaskActionApiIml mTaskActionApiIml;
    private ImageSelectorAdapter mImageSelectorAdapter;
    private BehaviorRecommendation mRecommendScheme;
    private CommonLabel selectorLeadLabel;
    private ArrayList<CommonLabel> Leaderlabels;
    private String TYPE_KEY;
    private TaskTypeAdapter mTaskCircleTypeAdapter;
    private boolean isself = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        toolbar.setNavigationOnClickListener(v -> onBackPressed());
        if (mTaskActionApiIml == null) {
            mTaskActionApiIml = TaskActionApiIml.getInstance();
        }
        initView();
        initdeliverData();
        initData();
    }

    //有关联  无关联  仅仅展示
    private void initdeliverData() {
        currentState = getIntent().getIntExtra(PAGESTATE, NOCORRELATE);
        schemeId = getStrExtra(ActionBaseBean.SCHEME_ID_KEY);
        questionId = getStrExtra(ActionBaseBean.QUESTION_ID_KEY);
        TYPE_KEY = getStrExtra(IntentUtils.ENTER_ACTIVITY_TYPE_KEY);
        taskFlowId = getStrExtra(ActionBaseBean.TASKFLOWID);
        if (currentState == CORRELATE) {
            questionId = getStrExtra(ActionBaseBean.QUESTION_ID_KEY);
            //如果有流程id的话 就是点击的add按钮 如果没有流程id的话
            //那就是点击的对应的流程 这里进来的话 这个页面就只能是查看的功能 所有要展示已经选择的问题图片 已经选择的方案图片
            //已经选择的负责人 和已经选择的周期
            mTaskActionApiIml.normal_question_page(questionId, "")
                    .subscribe(new NetWorkObserver<NormalQAPage>() {
                        @Override
                        protected void onFail(String errormsg) {
                            shortToast(errormsg);
                        }

                        @Override
                        protected void onSuccess(NormalQAPage result) {
                            if (!TextUtils.isEmpty(taskFlowId)) {
                                flowAddState(result);
                            } else {
                                edQuestion.setText(result.questionTitle);
                                edQuestion.setEnabled(false);
                                handleBtnState(result.buttons);
                                galleryAdapter.remove();
                                galleryAdapter.setonlydisplay();
                                mChoiceImages.addAll(result.questionImage);
                                for (String str : result.questionImage) {
                                    galleryAdapter.addImg(loadNormalImage(str));
                                }
                                //1展示标签已经选择好的标签 展示选择的方案 2 并且不能操作
                                initLabelClassifyData(result.selectedLabels);
                                setLabelsAllEnable(labels, false);
                                showSelectScheme(result.selectedScheme);
                                //2展示选择的负责人
                                showLeadLabel(result.mUserLeader);
                                //3 展示选择的周期
                                showSelectCycle(result.circleTypeList, result.startWeekendKey, result.endWeekendKey);
                            }
                        }
                    });
        } else if (currentState == NOCORRELATE) {
            mTaskActionApiIml.normal_question_page(questionId, schemeId)
                    .subscribe(new NetWorkObserver<NormalQAPage>() {
                        @Override
                        protected void onFail(String errormsg) {
                            shortToast(errormsg);
                        }

                        @Override
                        protected void onSuccess(NormalQAPage result) {
                            if (!TextUtils.isEmpty(questionId)) {
                                //只能操作选择的标签 然后选择方案图片
                                edQuestion.setText(result.questionTitle);
                                edQuestion.setEnabled(false);
                                galleryAdapter.remove();
                                galleryAdapter.setonlydisplay();
                                mChoiceImages.addAll(result.questionImage);
                                for (String str : result.questionImage)
                                    galleryAdapter.addImg(loadNormalImage(str));
                                showLeadLabel(result.mUserLeader);
                                showSelectCycle(result.circleTypeList, result.startWeekendKey, result.endWeekendKey);
                                showSelectScheme(result.selectedScheme);
                                initLabelClassifyData(result.selectedLabels);
                                initSelectLabel(result.initLabelModule);
                                setLabelsAllEnable(labels, false);
                                setLabelsAllSelected(labels, true);
                                currentState = ONLYDISPLAY;
                                handleBtnState(result.buttons);
                            }
                            if (!TextUtils.isEmpty(schemeId)) {
                                //展示选择的方案 并且标签就不展示了
                                showSelectScheme(result.selectedScheme);
                                initLabelClassifyData(result.selectedLabels);
                                initSelectLabel(result.initLabelModule);
                                setLabelsAllEnable(labels, true);
                                setLabelsAllSelected(labels, true);
                                initLabelCycleData(result.circleTypeList);
                                isHandle=false;
                            }
                            if (TextUtils.isEmpty(schemeId) && TextUtils.isEmpty(questionId)) {
                                initLabelClassifyData(result.initLabelModule);
                                initLabelCycleData(result.circleTypeList);
                            }
                        }
                    });
        } else if (currentState == ONLYDISPLAY) {
            //会有方案id 会问题id的
            questionId = getStrExtra(ActionBaseBean.QUESTION_ID_KEY);
            if (TextUtils.isEmpty(questionId)) {
                return;
            }
            //有问题 有方案 从下一步进来的 只能看 什么都不能操作
            mTaskActionApiIml.normal_question_page(questionId, schemeId)
                    .subscribe(new NetWorkObserver<NormalQAPage>() {
                        @Override
                        protected void onFail(String errormsg) {
                            shortToast(errormsg);
                        }

                        @Override
                        protected void onSuccess(NormalQAPage result) {
                            edQuestion.setText(result.questionTitle);
                            edQuestion.setEnabled(false);
                            //展示问题图片 展示选择标签和选择的方案
                            // 展示选择的领导
                            //展示选择的周期
                            galleryAdapter.remove();
                            galleryAdapter.setonlydisplay();
                            for (String str : result.questionImage)
                                galleryAdapter.addImg(loadNormalImage(str));
                            showLeadLabel(result.mUserLeader);
                            showSelectCycle(result.circleTypeList, result.startWeekendKey, result.endWeekendKey);
                            showSelectScheme(result.selectedScheme);
                            initLabelClassifyData(result.selectedLabels);
                            setLabelsAllEnable(labels, false);
                        }
                    });
        }
    }

    private void showSelectCycle(List<TaskType> listType, String start, String end) {
        Integer startvalue = Integer.parseInt(start);
        Integer endvalue = Integer.parseInt(end);
        for (TaskType taskType : listType) {
            Integer taskvalue = Integer.parseInt(taskType.getValue());
            if (taskvalue >= startvalue && taskvalue <= endvalue) {
                taskType.setSelected(true);
            } else {
                taskType.setEnable("0");
            }
        }
        mTaskCircleTypeAdapter.setOnlyShow();
        mTaskCircleTypeAdapter.setTypeList(listType);
    }

    private void showLeadLabel(UserLeader userLeader) {
        selectUser.setVisibility(View.INVISIBLE);
        Leaderlabels.clear();
        if (AccountHelper.getUid().equals(userLeader.uid)) {
            Leaderlabels.add(new CommonLabel(AccountHelper.getUid(), "自己"));
        } else if (TextUtils.isEmpty(userLeader.uid)) {
              Leaderlabels.add(new CommonLabel("", "组织内张榜"));
        } else if(in_the_team.equals(userLeader.uid)){
             Leaderlabels.add(new CommonLabel(in_the_team, "团队内张榜"));
        } else {
            Leaderlabels.add(new CommonLabel(userLeader.uid, userLeader.username));
            btnNextStep.setEnabled(false);
            btnReceiveQuestion.setEnabled(false);
        }
        initLabelLeadData(Leaderlabels);
        leadLabel.setSelects(0);
    }

    private void showSelectScheme(BehaviorRecommendation scheme) {
        if (null != scheme.schemeId && null != scheme.schemeImage) {
            List<BehaviorRecommendation> temp = new ArrayList<>();
            temp.add(scheme);
            mRecommendScheme = scheme;
            mImageSelectorAdapter.setSelectSchemes(temp);
        }
    }

    private void flowAddState(NormalQAPage result) {
        initLabelClassifyData(result.initLabelModule);
        initLabelCycleData(result.circleTypeList);
    }

    private void handleBtnState(NormalQAPage.ButtonsBean buttons) {

//        if (!"1".equals(buttons.nextStepBt)) {
//            //不能修改问题图 不能选择负责人 不能选择周期 不能选择标签 不能点击下一步
//            setLabelsAllEnable(labels, false);
//            btnNextStep.setEnabled(false);
//            if (galleryAdapter != null) {
//                galleryAdapter.setonlydisplay();
//            }
//            leadLabel.setLabelsViewsEnable(false);
//        }
        if ("1".equals(buttons.canReceive)) {
            btnNextStep.setVisibility(View.GONE);
            btnReceiveQuestion.setVisibility(View.VISIBLE);
            setLabelsAllEnable(labels, true);
        } else {
            btnReceiveQuestion.setVisibility(View.GONE);
            btnNextStep.setVisibility(View.VISIBLE);
        }
    }

    private static final int COLUMN = 4;

    private void initData() {
        mTaskCircleTypeAdapter = new TaskTypeAdapter();
        mTaskCircleTypeAdapter.setSelected(TaskTypeAdapter.SERIALSELECTED);
        GridLayoutManager layoutManager = new GridLayoutManager(this, COLUMN, GridLayoutManager.VERTICAL, false);
        cycleSelect.setNestedScrollingEnabled(false);
        cycleSelect.setLayoutManager(layoutManager);
        cycleSelect.addItemDecoration(new GridSpacingItemDecoration(COLUMN, getResources().getDimensionPixelSize(R.dimen.padding_default_min), false));
        cycleSelect.setAdapter(mTaskCircleTypeAdapter);
    }

    private void initLabelLeadData(List<CommonLabel> module) {
        leadLabel.setHook(false);
        leadLabel.setFork(false);
        leadLabel.setLabels(module, (label, position, data) -> data.label);
        leadLabel.setOnLabelClickListener((label, data, position) -> {
            selectorLeadLabel = module.get(position);
            if (position != 0) {
                isself = false;
//                selectView.setVisibility(View.GONE);
                btnNextStep.setText(getString(R.string.release));
            } else {
                isself = true;
//                selectView.setVisibility(View.VISIBLE);
                btnNextStep.setText(getString(R.string.next_step));
            }
        });
    }

    private void initLabelCycleData(List<TaskType> module) {
        mTaskCircleTypeAdapter.setTypeList(module);
    }

    private void initLabelClassifyData(List<CommonLabel> module) {
        if (module == null || module.size() != 6)
            return;
        initSelectLabel(module);
        selectorLabel = module;
        setLabelsAllEnable(labels, false);
        setLabelsEnable(labels, 0, true);
        setLabelsViewText(module, labels);
        for (int position = 0; position < labels.length; position++)
            labels[position].setOnClickListener(new LabelsTextOnClickListener(position, labels));
    }

    private void initSelectLabel(List<CommonLabel> module) {
        initListLabel.clear();
        Iterator<CommonLabel> iterator = module.iterator();
        while (iterator.hasNext()) {
            initListLabel.add(iterator.next().clone());
        }
    }

    private void initSchemeImage() {
        showWaitDiaLog();
        String arrayStr = new Gson().toJson(selectorLabel);
        mTaskActionApiIml.label_question_search("", arrayStr)
                .subscribe(new NetWorkObserver<List<BehaviorRecommendation>>() {
                    @Override
                    protected void onFail(String errormsg) {
                        hideWaitDialog();
                        shortToast(errormsg);
                    }

                    @Override
                    protected void onSuccess(List<BehaviorRecommendation> result) {
                        hideWaitDialog();
                        mImageSelectorAdapter.setRecommendSchemes(result);
                    }
                });
    }

    private PublishSubject<CommonLabel> initOptionsLabel(List<CommonLabel> result, int size) {
        PublishSubject<CommonLabel> subject = PublishSubject.create();
        List<CommonLabel> options1Items = new ArrayList<>();
        List<List<CommonLabel>> options2Items = new ArrayList<>();
        List<List<List<CommonLabel>>> options3Items = new ArrayList<>();
        for (CommonLabel label : result) {
            options1Items.add(label);
            ArrayList<CommonLabel> temp = new ArrayList<>();
            List<List<CommonLabel>> temp2 = new ArrayList<>();
            if (label.msubList.size() > 0) {
                temp.addAll(label.msubList);
            } else {
                if (size > 1)
                    temp.addAll(Collections.singletonList(label));
                if (size > 2)
                    temp2.addAll(Collections.singletonList(Collections.singletonList(label)));
            }
            for (CommonLabel labelChild : label.msubList) {
                ArrayList<CommonLabel> temp3 = new ArrayList<>();
                if (labelChild.msubList.size() > 0) {
                    temp3.addAll(labelChild.msubList);
                } else {
                    if (size > 2)
                        temp3.addAll(Collections.singletonList(labelChild));
                }
                temp2.add(temp3);
            }
            options2Items.add(temp);
            options3Items.add(temp2);
        }
        OptionsPickerView<CommonLabel> pvLabelOptions = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            CommonLabel key = null;
            switch (size) {
                case 1:
                    key = options1Items.get(options1);
                    break;
                case 2:
                    key = options2Items.get(options1).get(options2);
                    break;
                case 3:
                    key = options3Items.get(options1).get(options2).get(options3);
                    break;
            }
            subject.onNext(key);
        })
                .setTitleText(getString(R.string.label_selector))
                .setCancelColor(Color.GRAY)
                .setSubmitColor(getResources().getColor(R.color.lightorange))
                .setTextColorCenter(Color.LTGRAY)
                .build();
        switch (size) {
            case 1:
                pvLabelOptions.setPicker(options1Items);
                break;
            case 2:
                pvLabelOptions.setPicker(options1Items, options2Items);
                break;
            case 3:
                pvLabelOptions.setPicker(options1Items, options2Items, options3Items);
                break;
        }
        pvLabelOptions.show();
        return subject;
    }

    private void initView() {
        labels = new TextView[]{label1, label2, label3, label4, label5, label6};
        initImageSelector();
        selectView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        selectView.addItemDecoration(new SpacesItemDecoration(this, R.dimen.padding_default_min, LinearLayoutManager.HORIZONTAL));
        selectView.setAdapter(mImageSelectorAdapter = new ImageSelectorAdapter());
        mImageSelectorAdapter.getSelector()
                .subscribe(scheme -> mRecommendScheme = scheme);

        Leaderlabels = new ArrayList<>();
        Leaderlabels.add(new CommonLabel(AccountHelper.getUid(), "自己"));
        Leaderlabels.add(new CommonLabel(In_the_organization, "组织内张榜"));
        Leaderlabels.add(new CommonLabel(in_the_team, "团队内张榜"));
        initLabelLeadData(Leaderlabels);
    }

    private void initImageSelector() {
        List<View> imageViews = new ArrayList<>();
        imageViews.add(loadAddImage());
        galleryAdapter = new ImageNormalAdapter(imageViews);
        mViewPager.setAdapter(galleryAdapter);
    }

    private ArrayList<String> tempImageCache;
    boolean state = false;

    // TODO: 2018/6/29 新加入一个部门id
    private void releaseData() {
        //问题id 没有传空 managerUid 指定人(自己 其他人 不指定)
        //descLabel 描述标签 detail 描述内容
        //任务周期选择
//        List<CommonLabel> cycleLabels = cycleLabel.getSelectLabelDatas();
        //负责人选择
        List<CommonLabel> leadLabels = leadLabel.getSelectLabelDatas();
        //图片的话 要是新建问题 还有从我要学进来的 就要先上传图片 然后上传其他信息
        AddQuestion addQuestion = new AddQuestion()
                .setTitle(ViewUtils.text(edQuestion))
                .setQuestionId(questionId)
                .setDescLabel(new Gson().toJson(selectorLabel))
                .setCycleTypes(mTaskCircleTypeAdapter.getSelected())
                .setManagerUid(leadLabels.get(0).key);
       if (in_the_team.equals(leadLabels.get(0).key)){
            addQuestion.setDepartmentId(AccountHelper.getDepartmentid());
       }
        if (!TextUtils.isEmpty(taskFlowId)) {
            addQuestion.setTaskFlowId(taskFlowId);
        }
        if (mRecommendScheme != null) {
            //上传标签的描述
            addQuestion.setSchemeId(mRecommendScheme.schemeId);
        }
        showWaitDiaLog();
        Observable.just(mChoiceImages)
                .map(strings -> {
                    state = false;
                    for (String imgurl : mChoiceImages) {
                        if (imgurl.startsWith("http")) {
                            state = true;
                            break;
                        }
                    }
                    if (state) {
                        return mChoiceImages;
                    }
                    ArrayList<String> tempImageCache = new ArrayList<>();
                    for (int i = 0; i < strings.size(); i++) {
                        Bitmap bitmap = BitmapFactory.decodeFile(strings.get(i));
                        File file = BitmapUtils.changeBitmap2File(bitmap,
                                ActionSetting1Activity.this, i + "temp.jpeg");
                        tempImageCache.add(file.getPath());
                    }
                    return tempImageCache;
                })
                .subscribeOn(Schedulers.io())
                .flatMap(strings -> {
                    if (state) {
                        List<ImgBean> beans = new ArrayList<>();
                        for (String imgurl : mChoiceImages) {
                            beans.add(new ImgBean(imgurl));
                        }
                        return Observable.just(beans);
                    } else {
                        return UserManageDataApiStoreIml.getInstance().uploadImgs(strings);
                    }
                })
                .flatMap(beans -> {
                    ArrayList<String> strings = new ArrayList<>();
                    for (ImgBean bean : beans) {
                        strings.add(bean.getImgUrl());
                    }
                    addQuestion.setImgs(strings);
                    return mTaskActionApiIml.add_normal_question(addQuestion);
                })
                .subscribe(new NetWorkObserver<String>() {
                    @Override
                    protected void onFail(String errormsg) {
                        shortToast(errormsg);
                        hideWaitDialog();
                    }
                    @Override
                    protected void onSuccess(String result) {
                        hideWaitDialog();
                        //todo 貌似是不一定要进入下一步的东西
                        if (ConstantsState.isResultOk(result)) {
                            if (!isself) {
                                finish();
                                shortToast(getString(R.string.submit_ok_please));
                                return;
                            }
                            shortToast(getString(R.string.submit_ok));
                            currentState = ONLYDISPLAY;
                            Intent intent = new Intent(getBaseContext(), ActionDetailTxtCreateActivity.class);
                            if (!TextUtils.isEmpty(TYPE_KEY)) {
                                intent.putExtra(IntentUtils.ENTER_ACTIVITY_TYPE_KEY, TYPE_KEY);
                            }
                            questionId = result;
                            intent.putExtra(ActionBaseBean.ACTION_ID_KEY, result);
                            startActivity(intent);
                        } else {
                            shortToast(getString(R.string.submit_fail));
                        }
                    }
                });
    }

    private void checkInput() throws ValidateException {
        if (TextUtils.isEmpty(ViewUtils.text(edQuestion))) {
            throw new ValidateException(getString(R.string.question_please_input_title));
        }
        //选择问题图片
        if (mChoiceImages.size() == 0) {
            throw new ValidateException(getString(R.string.please_select_image));
        }
        //选择负责人
        if (leadLabel.getSelectLabelDatas().size() == 0) {
            throw new ValidateException(getString(R.string.question_please_selector_leader));
        }

        if (!isAllSelector(labels)) {
            throw new ValidateException(getString(R.string.scheme_not_null_label));
        }
        if (mTaskCircleTypeAdapter.getSelected().isEmpty()) {
            throw new ValidateException(getString(R.string.taskcircletype_not_null));
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        currentState = intent.getIntExtra(PAGESTATE, NOCORRELATE);

    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_action_setting1;
    }


    @OnClick(R.id.btn_next_step)
    public void NextStepClicked() {
        try {
            if (currentState == ONLYDISPLAY || currentState == CORRELATE) {
                Intent intent = new Intent(getBaseContext(), ActionDetailTxtCreateActivity.class);
                if (!TextUtils.isEmpty(TYPE_KEY)) {
                    intent.putExtra(IntentUtils.ENTER_ACTIVITY_TYPE_KEY, TYPE_KEY);
                }
                intent.putExtra(ActionBaseBean.ACTION_ID_KEY, questionId);
                startActivity(intent);
                return;
            }
            checkInput();
            if (mChoiceImages.size() < 3) {
                //弹出dialog提示信息
                DialogUtils.showSureDialog(this, getText(R.string.action_submit_hint_msg).toString(),
                        dialog -> releaseData());
            } else {
                releaseData();
            }
        } catch (ValidateException e) {
            shortToast(e.getMessage());
        }

    }

    @Override
    public void onBackPressedWithoutDialog() {
        DialogUtils.showSureDialog(this, getString(R.string.lost_data), dialog -> finish());
    }

    @OnClick(R.id.select_user)
    public void onSelectUserClicked() {
        Intent intent = new Intent(this, UserListChosenActivity.class);
        intent.putExtra(ChosenChargeJoinAdapterHolder.ENTER_TYPE_KEY, ChosenChargeJoinAdapterHolder.TYPE_CHOSEN_MANAGE);
        intent.putExtra(ConstantsState.CHOSEN_USER_TYPE_KEY, ConstantsState.CHOSEN_ACTION_USER_TYPE);
        intent.putExtra(UserListChosenActivity.ENTER_CHOSEN_TYPE_KEY, UserListChosenActivity.ENTER_CHOSEN_TYPE_UNLIMITED);
        intent.putExtra(ConstantsState.SERVER_ID_KEY, taskFlowId);
        startActivityForResult(intent, CREATE_TARGET_PAGER);
    }

    @OnClick(R.id.btn_receive_question)
    public void receiveQuestionClicked() {
        DialogUtils.showSureDialog(this, getString(R.string.examine_hint),
                new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                receiveQuestion();
            }
        });

    }

    private void receiveQuestion() {
        showWaitDiaLog();
        mTaskActionApiIml.receive_question(questionId, new Gson().toJson(selectorLabel), mRecommendScheme != null ? mRecommendScheme.schemeId : "")
                .subscribe(new NetWorkObserver<String>() {
                    @Override
                    protected void onFail(String errormsg) {
                        hideWaitDialog();
                        shortToast(errormsg);
                    }
                    @Override
                    protected void onSuccess(String result) {
                        hideWaitDialog();
                        if (ConstantsState.isResultOk(result)) {
                            shortToast(getString(R.string.success_getquestion));
                            finish();
                        }
                    }
                });
    }


    @OnClick(R.id.label_detial)
    public void labelDetialClicked() {
        //展示已经选择标签的详情 也就是展示selectorLabel列表的内容
        AlertDialog.Builder normalDialog = new AlertDialog.Builder(this);
        View view=View.inflate(this,R.layout.dialog_list,null);
        ListView listView=view.findViewById(R.id.tv_list);
        TextView sure=view.findViewById(R.id.tv_sure);
        TextView title=view.findViewById(R.id.tv_title);
        title.setText(getString(R.string.label_list));
        ArrayList<String> strings=new ArrayList<>();
        for (CommonLabel commonLabel:selectorLabel){
            strings.add(commonLabel.label);
        }
        listView.setAdapter(new LabelDailogAdapter(this,strings));
        normalDialog.setView(view);
        AlertDialog dialog=normalDialog.show();
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    private class ImageNormalAdapter extends StaticPagerAdapter {
        private List<View> mBannerList;
        private int IMGSIZE = 4;
        private boolean onlydisplay = false;

        public void setonlydisplay() {
            this.onlydisplay = true;
        }

        ImageNormalAdapter(List<View> bannerList) {
            mBannerList = bannerList;
        }

        void remove() {
            mBannerList.clear();
        }

        void setimg(int index, View imageView) {
            mBannerList.set(index, imageView);
            notifyDataSetChanged();
        }

        void addImg(View imageView) {
            mBannerList.add(0, imageView);
            if (mBannerList.size() >= IMGSIZE) {
                mBannerList.remove(mBannerList.size() - 1);
                Collections.reverse(mBannerList);
            }
            notifyDataSetChanged();
        }

        @Override
        public View getView(ViewGroup container, int position) {
            View view = mBannerList.get(position);
            if (onlydisplay) {
                view.setEnabled(false);
            }
            return view;
        }

        @Override
        public int getCount() {
            return mBannerList.size();
        }
    }

    public ImageView loadNormalImage(final String url) {
        ImageView item = new ImageView(this);
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(-1, -1);
        item.setLayoutParams(params);
        item.setScaleType(ImageView.ScaleType.CENTER_CROP);
        Glide.with(ActionSetting1Activity.this).load(url).asBitmap()
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                        item.setImageBitmap(resource);
                    }
                });
        item.setOnClickListener(v ->
                AlbumUtils.singleChoice(getBaseContext())
                        .subscribe(albumFile -> {
                            if (!mChoiceImages.contains(albumFile.getPath())) {
                                int index = mChoiceImages.indexOf(url);
                                mChoiceImages.set(index, albumFile.getPath());
                                galleryAdapter.setimg(index, loadNormalImage(albumFile.getPath()));
                            } else {
                                shortToast(getString(R.string.already_choice_image));
                            }
                        }));
        return item;
    }

    public View loadAddImage() {
        LinearLayout container = new LinearLayout(this);
        LinearLayout.LayoutParams containerparams = new LinearLayout.LayoutParams(-1, -1);
        container.setBackgroundColor(getResources().getColor(R.color.white));
        container.setLayoutParams(containerparams);
        container.setGravity(Gravity.CENTER);

        ImageView item = new ImageView(this);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-2, -2);
        item.setLayoutParams(params);
        item.setImageResource(R.drawable.add_question_img);
        item.setOnClickListener(v -> openAlbum());
        container.addView(item);

        return container;
    }

    private void openAlbum() {
        AlbumUtils.multipleChoice(this, 3 - mChoiceImages.size())
                .subscribe(albumFile -> {
                    if (!mChoiceImages.contains(albumFile.getPath())) {
                        mChoiceImages.add(0, albumFile.getPath());
                        galleryAdapter.addImg(loadNormalImage(albumFile.getPath()));
                    } else {
                        shortToast(getString(R.string.already_choice_image));
                    }
                     if (mChoiceImages.size() == 3) {
                        Collections.reverse(mChoiceImages);
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode != CREATE_TARGET_PAGER)
            return;
        switch (resultCode) {
            case CHOSE_CHARGE:
                PersonUserBean result = (PersonUserBean) data.getSerializableExtra(CHARGE_KEY);
                if (Leaderlabels.size() >= 4) {
                    Leaderlabels.remove(Leaderlabels.size() - 1);
                }
                Leaderlabels.add(new CommonLabel(result.getUid(), result.getNickName()));
                initLabelLeadData(Leaderlabels);
                leadLabel.setSelects(Leaderlabels.size() - 1);
                isself = false;
                selectView.setVisibility(View.GONE);
                btnNextStep.setText(getString(R.string.release));
                break;

        }
    }

    private void setLabelsAllEnable(TextView[] labelsView, boolean enable) {
        for (TextView text : labelsView) {
            text.setEnabled(enable);
        }
    }

    private void setLabelsEnable(TextView[] labelsView, int position, boolean enable) {
        labelsView[position].setEnabled(enable);
    }

    private void setLabelsAllSelected(TextView[] labelsView, boolean enable) {
        for (TextView text : labelsView) {
            text.setSelected(enable);
        }
    }

    private boolean isAllSelector(TextView[] labelsView) {
        boolean tempstate = true;
        for (TextView s : labelsView) {
            if (!s.isSelected()) {
                tempstate = false;
            }
        }
        return tempstate;
    }

    private void setLabelsViewText(List<CommonLabel> labels, TextView[] labelsView) {
        labelsRoot_5 = labels.get(3).key;
        for (int index = 0; index < labels.size(); index++) {
            labelsView[index].setText(labels.get(index).getPickerViewText());
        }
    }

    class LabelsTextOnClickListener implements View.OnClickListener {

        private int position;
        private TextView[] labelsView;

        public LabelsTextOnClickListener(int position, TextView[] labelsView) {
            this.position = position;
            this.labelsView = labelsView;
        }

        @Override
        public void onClick(View v) {
            String rootId;
            if (position != 4)
                rootId = initListLabel.get(position).key;
            else
                rootId = labelsRoot_5;

            mTaskActionApiIml.sub_label_list(rootId)
                    .subscribe(new NetWorkObserver<List<CommonLabel>>() {
                        @Override
                        public void onFail(String errormsg) {
                            shortToast(errormsg);
                        }

                        @Override
                        public void onSuccess(List<CommonLabel> result) {
                            initOptionsLabel(result, MathUtils.getCyclerSize(result, 0))
                                    .subscribe(labels -> {
                                        selectorLabel.set(position, labels);
                                        labelsView[position].setText(labels.getPickerViewText());
                                        labelsView[position].setSelected(true);
                                        if (isAllSelector(labelsView)) {
                                            if (isHandle)
                                               initSchemeImage();
                                        }
                                        if (labelsView.length > position + 1) {
                                            if (!labelsView[position + 1].isEnabled())
                                                labelsView[position + 1].setEnabled(true);
                                            if (position == 3 && labelsView[4].isEnabled()) {
                                                labelsRoot_5 = labels.key;
                                                labelsView[4].setSelected(false);
                                                selectorLabel.set(position + 1, new CommonLabel(getString(R.string.label_unknown)));
                                                initListLabel.set(position + 1, new CommonLabel(getString(R.string.label_unknown)));
                                                labelsView[4].setText(getString(R.string.label_unknown));
                                            }
                                        }
                                    });
                        }
                    });
        }
    }


}
